/**
 * @description 通用工具函数
 */

type IScopeKey = keyof WechatMiniprogram.OpenSettingSuccessCallbackResult['authSetting']

export { default as qrCode } from './wxqrcode'

/** 获取菜单按钮（右上角胶囊按钮）的布局位置信息 */
export const getMenuButtonBoundingClientRect = (() => {
  let value: any = null
  return () => {
    if (value && value.top && value.height) {
      return value
    }
    value = wx.getMenuButtonBoundingClientRect()
    return value
  }
})()

/** 处理多个路径末尾拼接时多个斜杠的问题, 如果第一个数组是有一个斜杠需要拼接上, 如果最后一个有斜杠则去掉 */
export function joinPath(...paths: (string | number)[]) {
  const path = paths
    .map((path, index) => {
      const newPath = path != null ? `${path}` : ''
      if (index === 0) {
        return newPath.replace(/\/$/, '')
      }
      return newPath.replace(/(^\/|\/$)/g, '')
    })
    .filter((path) => path)
    .join('/')
  if (!path.startsWith('/') && `${paths[0]}`.startsWith('/')) {
    return `/${path}`
  }
  return path
}

// 判断是否是http或者https地址
export function isHttp(url: string) {
  return /^(http|https):\/\//.test(url)
}

/** 授权的判断处理, 并打开授权页 */
export function authBool(callback: any, scopeKey: IScopeKey = 'scope.writePhotosAlbum') {
  wx.getSetting({
    success(res: any) {
      //  = 'scope.writePhotosAlbum'
      if (res.authSetting[scopeKey] !== false) {
        callback('success')
        return
      } else {
        wx.openSetting({
          success(res) {
            if (res.authSetting[scopeKey] !== false) {
              callback('success')
            } else {
              callback('fail')
            }
          },
          fail() {
            callback('fail')
          },
        })
      }
    },
    fail() {
      callback('fail')
    },
  })
}

/** url参数处理 */
export function urlParse(url: string) {
  let urlParse = decodeURIComponent(`${url}`)
  let urlParseObj: any = {}
  if (url && urlParse.length > 1) {
    const itemArr = urlParse.split('=')
    urlParseObj[itemArr[0]] = itemArr[1]
  }
  return urlParseObj
}

/** 返回上一页 */
export function goBack() {
  getCurrentPages().length > 1
    ? wx.navigateBack()
    : wx.reLaunch({
        url: '/pages/index/index',
      })
}

/** 获取系统信息 */
export const getSystemInfoSync = (() => {
  let data: WechatMiniprogram.SystemInfo | null = null
  return () => {
    if (data === null) {
      data = wx.getSystemInfoSync()
    }
    return data
  }
})()

/** rpx转px */
export const rpxToPx = (value = 0): number => {
  return (value / 750) * getSystemInfoSync().windowWidth
}

/** px转rpx */
export const pxToRpx = (value = 0): number => {
  return (value * 750) / getSystemInfoSync().windowWidth
}

/** 验证手机号 */
export function isPhone(phone: string) {
  return /^1[3456789]\d{9}$/.test(`${phone}`)
}

/** json字符串转对象 */
export function jsonParse(str: string) {
  try {
    return JSON.parse(str)
  } catch (error) {
    return str
  }
}

